<template>
  <div>
    <el-card class="elCard" style="height: 80px">
      <el-form class="search-form" ref="resetRef" :model="searchParams">
        <el-form-item label="用户名：" prop="userName">
          <el-input placeholder="请输入用户名" v-model="searchParams.userName"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchUserList">搜索</el-button>
          <el-button type="primary" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="elCard">
      <el-button type="primary" @click="saveUser">添加</el-button>
      <el-button type="primary" @click="batchDeleteUser(selectUserIdList)" :disabled="selectUserIdList.length<=0">
        批量删除
      </el-button>
      <el-table :data="userList" @selection-change="handleSelectionChange">
        <el-table-column type="selection"></el-table-column>
        <el-table-column label="用户编号" prop="userId" align="center"></el-table-column>
        <el-table-column label="用户名称" prop="userName" align="center"></el-table-column>
        <el-table-column label="用户昵称" prop="nickName" align="center"></el-table-column>
        <el-table-column label="部门" prop="dept.deptName" align="center"></el-table-column>
        <el-table-column label="手机号码" prop="phonenumber" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-switch :active-value="!scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" align="center"></el-table-column>
        <el-table-column label="操作" width="200px" align="center">
          <template #default="scope">
            <el-button type="primary" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="primary" @click="batchDeleteUser([scope.row.userId])">删除</el-button>
          </template>

        </el-table-column>
        <template #empty>
          数据为空
        </template>
      </el-table>
      <el-pagination
          style="margin-top: 10px"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :background="true"
          layout="prev, pager, next, jumper,->,sizes,total"
          :page-sizes="[1,5,10]"
          :total="total"
          @size-change="updateSize"
          @current-change="updatePage"
      />
    </el-card>


    <el-dialog
        v-model="showSaveOrUpdateDialog"
        title="Tips"
        width="600px"
    >
      <template #header>
        {{ userParam.userId ? "修改用户" : "保存用户" }}
      </template>

      <!--      label-width="auto"-->
      <!--      标签长度，如果不设置，会对不齐-->
      <el-form label-width="90px" :model="userParam" :rules="userRules" ref="userFormRef">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户昵称" prop="nickName">
              <el-input v-model="userParam.nickName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userParam.email"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="userParam.userName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!userParam.userId">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="userParam.password"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select v-model="userParam.sex" placeholder="请选择性别">
                <el-option
                    v-for="item in [{value:'0',label:'男'},{value:'1',label:'女'},{value:'2',label:'未知'}]"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="userParam.status">
                <el-radio value="0">正常</el-radio>
                <el-radio value="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" style="width: 100%">
              <el-input type="textarea" v-model="userParam.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showSaveOrUpdateDialog = false">取消</el-button>
          <el-button type="primary" @click="submitUserForm">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ElCard,
  ElInput,
  ElForm,
  ElFormItem,
  ElButton,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElSwitch,
  ElDialog,
  ElRadioGroup,
  ElRadio,
  ElCol,
  ElRow, ElMessage
} from "element-plus"
import {nextTick, onMounted, reactive, ref} from "vue";
import {getUserList, addUser, updateUser, deleteUser} from "@/api/user/user.js"


let searchParams = ref({
  pageNum: 1,
  pageSize: 10,
  userName: ""
})

onMounted(() => {
  fetchUserList()
})

let currentPage = ref(1)
let pageSize = ref(10)
let total = ref(0)
let userList = ref([])
let fetchUserList = () => {
  getUserList(searchParams.value)
      .then(resp => {
        if (resp.code === 200) {
          userList.value = resp.rows
          total = resp.total
        }
      })
}

let updateSize = (pageSize) => {
  searchParams.value.pageSize = pageSize
  fetchUserList()
}

let updatePage = pageNum => {
  searchParams.value.pageNum = pageNum
  fetchUserList()
}

let selectUserIdList = ref([])
const handleSelectionChange = (userList) => {
  selectUserIdList.value = userList.map(item => item.userId)
  console.log(selectUserIdList.value)
}

let resetRef = ref()
let reset = () => {
  resetRef.value.resetFields()
}

//是否显示新增修改弹窗
let showSaveOrUpdateDialog = ref(false)
let userParam = ref({})
let saveUser = () => {
  resetUserParam();
  showSaveOrUpdateDialog.value = true
  nextTick(() => {
    userFormRef.value.resetFields()
  })
}
const batchDeleteUser = userIdList => {
  if (!userIdList || userIdList.length <= 0) {
    return;
  }
  deleteUser(userIdList)
      .then(resp => {
        if (resp.code === 200) {
          ElMessage.success("删除成功")
          fetchUserList()
        }
      })

}
let resetUserParam = () => {
  userParam.value = {
    userName: "",
    nickName: "",
    password: "",
    email: "",
    sex: "",
    status: "",
    remark: ""
  }
}

const userFormRef = ref()
let submitUserForm = async () => {

  await userFormRef.value.validate()

  let resp;
  let successMsg;
  if (userParam.value.userId) {
    resp = await updateUser(userParam.value)
    successMsg = "修改成功"
  } else {
    resp = await addUser(userParam.value)
    successMsg = "新增成功"
  }

  if (resp.code === 200) {
    ElMessage.success(successMsg)
    showSaveOrUpdateDialog.value = false
    fetchUserList();
  }
}


let handleUpdate = (user) => {
  console.log(788, user)

  Object.assign(userParam.value, user)
  showSaveOrUpdateDialog.value = true
}

const nickNameValidator = (rule, value, callback) => {
  if (!value || value.trim() === '') {
    callback(new Error('用户昵称不能为空'))
  } else {
    callback()
  }
}

const userNameValidator = (rule, value, callback) => {
  if (!value || value.trim() === '') {
    callback(new Error('用户名称不能为空'))
  } else {
    callback()
  }
}
const passwordValidator = (rule, value, callback) => {
  if (!value || value.trim() === '') {
    callback(new Error('用户密码不能为空'))
  } else {
    callback()
  }
}
const emailValidator = (rule, value, callback) => {
  if (value) {
    // 定义一个常见的邮箱格式的正则表达式
    const emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/;
    if (!emailRegex.test(value)) {
      callback(new Error('请输入有效的邮箱'));
    }
  }

  callback()

}
let userRules = reactive({
  nickName: [{validator: nickNameValidator, trigger: "blur", required: true}],
  userName: [{validator: userNameValidator, trigger: "blur", required: true}],
  password: [{validator: passwordValidator, trigger: "blur", required: true}],
  email: [{validator: emailValidator, trigger: "blur"}]
})

</script>
<style scoped lang="scss">
.elCard {
  margin: 0 30px;
  margin-bottom: 10px;
}

.search-form {
  display: flex;
  justify-content: space-between;
  //align-items: center;
}
</style>